/*
 * playerlist.c
 *
 *  Created on: Jul 11, 2011
 *      Author: alemao
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include "player.h"

/*
static int total_lists = 0;
static playerlist *ld = NULL;
static player **lists = NULL;

static int find_listdescriptor(playerlist list){
	int i;

	if (!ld)
		return -1;

	for (i=0; ld[i]; i++)
		if (ld[i] == list)
			break;

	if (ld[i])
		return i;
	else return -1;
}


playerlist libplayer_create_playerlist(void){
	player *new_list = calloc(1, sizeof(player *));

	total_lists++;

	if (!ld || !lists)
	{
		ld = calloc( total_lists+1, sizeof(playerlist) );
		ld[total_lists] = 0;
		ld[total_lists-1] = 1;
		lists = calloc( total_lists+1, sizeof(player *) );
		lists[ld[total_lists-1]] = NULL;
	}
	else
	{
		ld = calloc( total_lists+1, sizeof(playerlist) );
		ld[total_lists] = 0;
		lists = realloc(lists, total_lists*sizeof(player *) );
	}
	return ld[total_lists-1];
}*/

/*
 *
 */
extern player **libplayer_createlist(void){
	player **List;

	List = malloc(sizeof(player *));
	if (errno == ENOMEM)
		return NULL;
	List[0]=NULL;

	return List;
}

/*
 *
 */
extern int libplayer_appendtolist(player ***list, player *Player)
{
	int i;
	player **List = *list;

	/* descobre o tamanho da lista*/
	for (i = 0; List[i]; i++);

	/* aumenta a memoria alocada*/
	*list = realloc(List, (i + 2)*sizeof(player *));
	if (errno == ENOMEM)
		return -1;

	/* copia ponteiro*/
	List = *list;
	List[i+1] = NULL;
	List[i] = Player;

//	for (i = 0; List[i]; i++);
//	printf("%s i = %d, size = %d\n", __FUNCTION__, i, (i + 2)*sizeof(player *));
	return 0;
}

extern int libplayer_findplayer(player **List, player *Player)
{
	int i;

	for (i = 0; List[i]; i++)
		if ( (List[i]->team == Player->team) &&
			(List[i]->class == Player->class) &&
			(!strcmp(List[i]->name, Player->name)) )
			break;
//	printf("%s i = %d\n", __FUNCTION__, i);
	if (List[i])
		return i;
	else return -1;
}

void libplayer_freelist(player **List){
	free(List);
}
